package cn.cxy.roomdemo

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async

class MainActivity : AppCompatActivity() {
    //记录最后一次新增的用户id，用于标识待更新的用户
    private var lastAddedUserId: Long = 0
    private lateinit var userDao: UserDao
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        userDao = AppDatabase.getInstance(this).userDao
        addDataBtn.setOnClickListener { addUser() }
        updateDataBtn.setOnClickListener { updateUser() }
        delDataBtn.setOnClickListener { delUser() }
        queryDataBtn.setOnClickListener { queryUser() }
    }

    private fun addUser() {
        GlobalScope.async {
            var result = userDao.add(User(name = "张三"))
            lastAddedUserId = result[0]
        }
    }

    private fun updateUser() {
        val user = User(id = lastAddedUserId, name = "李四")

        GlobalScope.async {
            userDao.update(user)
        }
    }

    private fun delUser() {
        GlobalScope.async {
            userDao.deleteAll()
        }
    }

    private fun queryUser() {
        GlobalScope.async {
            val dataList = userDao.query()
            if (dataList.isNotEmpty()) {
                dataList.forEach { Log.d("MainActivity", "用户：${it.name}") }
            } else {
                Log.d("MainActivity", "数据库是空的！")
            }
        }
    }
}